<?php

class AppController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // FrontlineSMS Http Trigger Action
            'httptrigger' => array(
                'class' => 'application.controllers.app.HttpTriggerAction',
            ),
            'priceinquiry' => array(
                'class' => 'application.controllers.app.PriceInquiryAction',
            ),
            'newcrop' => array(
                'class' => 'application.controllers.app.CropCreateAction',
            ),
            'newprice' => array(
                'class' => 'application.controllers.app.PriceCreateAction',
            ),
            'pricehistory' => array(
                'class' => 'application.controllers.app.PriceHistoryAction',
            ),
            'cropstatus' => array(
                'class' => 'application.controllers.app.CropStatusAction',
            ),
        );
    }

    public function actionEditor() {
        $this->render('editor');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionHome() {
        $model = new Crop('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Search']))
            $model->attributes = $_GET['Search'];

        $this->render('home', array(
            'model' => $model,
        ));
    }

    public function actionUpdatePrices() {
        $model = new Price;

        if (isset($_POST['Price'])) {
            
        }

        $sql = 'SELECT price.group_name, price.crop_alias, price.crop_price, price.price_effectivedatetime 
                FROM (SELECT c.alias AS crop_alias, p.value AS crop_price, p.timestamp as timestamp 
                            FROM crops AS c 
                            JOIN prices AS p ON c.id = p.crop_id 
                            JOIN groups AS g ON c.group_id = g.id 
                            WHERE c.is_active = 1';

        $dataProvider = new CActiveDataProvider('Crop', array(
                    'criteria' => array(
                        'select' => array('alias'),
                        'order' => 'alias ASC',
                        'with' => array(
                            'prices' => array(
                                'select' => 'value',
                                'order' => 'timestamp DESC',
                                'limit' => 1
                            )
                        ),
                    ),
                    'pagination' => array(
                        'pageSize' => 50,
                    ),
                ));

        $this->render('price_update', array(
            'model' => $model,
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $this->layout = '//layouts/guest';

        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('login', 'priceinquiry', 'error'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('updatePrices', 'home', 'httptrigger', 'newcrop', 'newprice', 'pricehistory', 'cropstatus', 'logout'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

}